package com.zto.sch.base.thread;

import java.util.concurrent.locks.LockSupport;

public class ThreadOddEvenLock_FangChao {
    /**
     * 资源
     */
    static class Resource {
        private volatile int i;

        public Resource(int i) {
            this.i = i;
        }

        public int getI() {
            return i;
        }

        public void setI(int i) {
            this.i = i;
        }
    }

    static class ThreadOdd implements Runnable {
        private Resource resource;

        public ThreadOdd(Resource resource) {
            this.resource = resource;
        }

        @Override
        public void run() {
            while (true) {
                int i = resource.getI();
                if (i > 100) {
                    break;
                }
                if (i % 2 != 0) {
                    System.out.println(Thread.currentThread().getName() + "---->" + i);
                    resource.setI(++i);
                    LockSupport.unpark(t2);
                } else {
                    LockSupport.park();
                }
            }
        }
    }

    static class ThreadEven implements Runnable {
        private Resource resource;

        public ThreadEven(Resource resource) {
            this.resource = resource;
        }

        @Override
        public void run() {
            while (true) {
                int i = resource.getI();
                if (i > 100) {
                    break;
                }
                if (i % 2 == 0) {
                    System.out.println(Thread.currentThread().getName() + "====>" + i);
                    resource.setI(++i);
                    LockSupport.unpark(t1);
                } else {
                    LockSupport.park();
                }
            }
        }
    }

    static Thread t1, t2;

    public static void main(String[] args) {
        Resource resource = new Resource(1);
        t1 = new Thread(new ThreadOdd(resource));
        t2 = new Thread(new ThreadEven(resource));

        t1.start();
        t2.start();
    }
}